Uec3.DepartmentWindow = Ext.extend(Ext.app.Module, {
	id : 'department',
	type : 'common/department',

	/**
	 * Initialize this module. This function is called at startup (page
	 * load/refresh).
	 */
	init : function(initParams) {

	},
	paramsCollection : new Ext.util.MixedCollection(true),

	getParamsByKey : function(key) {
		return this.paramsCollection.get(key);
	},
	browseDepartment : function(rowIndex) {

		    var department_ds = this.getParamsByKey('department_ds');		
		    var department_form = this.getParamsByKey('department_form');
		    var department_win = this.getParamsByKey('department_win');
		    
		    var record = department_ds.getAt(rowIndex);

			department_form.getForm().loadRecord(record);

			department_win.buttons[0].hide();

			department_win.buttons[1].hide();

			department_win.show();

			department_win.setTitle('浏览部门-按Esc退出');
			
		    var maskTopField = this.getParamsByKey('maskTopField');
			
			maskTopField.show();
			

		},

	 editDepartment : function(rowIndex) {

	 	
		    var department_ds = this.getParamsByKey('department_ds');		
		    var department_form = this.getParamsByKey('department_form');
		    var department_win = this.getParamsByKey('department_win');
		
			var record = department_ds.getAt(rowIndex);

			department_form.getForm().loadRecord(record);

			department_win.buttons[0].show();
			department_win.buttons[1].show();

			department_win.show();

			department_win.buttons[0].setText('更新');

			department_win.setTitle('编辑部门-按Esc退出');

		  

		},

	deleteDepartment : function(rowIndex) {

		    var department_ds = this.getParamsByKey('department_ds');		
		    var department_grid = this.getParamsByKey('department_grid');		    

		    var record = department_ds.getAt(rowIndex);

			Ext.Msg.confirm('信息', '确定要删除?', function(btn) {
						if (btn == 'yes') {
							department_grid.loadMask.show();
							var departmentId = record.get('id');
							Ext.Ajax.request({
										url : Uec3.App.Constants.homeUrl
												+ '/department/base!delete.do',
										success : function(res) {

											var result = res.responseText;
											if (!result) {
												department_ds.remove(record);
												// department_grid.getView()
												// .refresh();
												department_ds.reload();
												department_grid.loadMask.hide();
												Ext.Msg.alert("提示","删除成功");

											} else {
												department_grid.loadMask.hide();
												Ext.Msg
														.alert(
																"提示",
																Ext
																		.decode(result).failure);
											}
										},

										failure : function(res) {
											department_grid.loadMask.hide();
											Ext.Msg.alert('网络异常,请重先请求');

										},

										params : {
											id : departmentId
										}

									});

						}
					});
		},
		revertDepartment:function(rowIndex){
			
		    var department_ds = this.getParamsByKey('department_ds');		
		    var department_grid = this.getParamsByKey('department_grid');	
	        var record = department_ds.getAt(rowIndex);
			var departmentId = record.get('id');
			Ext.Ajax.request({
				url : Uec3.App.Constants.homeUrl
						+ '/department/base!revertDepartment.do',
				success : function(res) {

					var result = res.responseText;
					if (!result) {
						department_ds.remove(record);

						department_ds.reload();
						department_grid.loadMask.hide();
						Ext.Msg.alert("提示","恢复成功");

					} else {
						department_grid.loadMask.hide();
						Ext.Msg
								.alert(
										"提示",
										Ext
												.decode(result).failure);
					}
				},

				failure : function(res) {
					department_grid.loadMask.hide();
					Ext.Msg.alert('网络异常,请重先请求');

				},

				params : {
					id : departmentId
				}

			});
			
		},
	getComponents : function(module) {

		var department_ds;
		var department_grid;
		var department_win;
		var department_form;
		var department_ajax;
		var keymap;
		var navigation;

		function renderDesc(value, cellmeta, record, rowIndex, columnIndex,
				store) {
            var str;
			
			var isDelete = record.get("isDelete");
			var i=record.get("isDefault");
			if (module.app.hasPermission(14)) {

				if (isDelete==1) {

					str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"department\").browseDepartment("
							+ rowIndex
							+ ");'>查看</a>|"
							+ "<a style='font-size:12px;margin-left:12px' href='javascript:Ext.CUR_APP.getModule(\"department\").revertDepartment("
							+ rowIndex + ");'>恢复</a>|"

				} else {
					
					if(i==1){
						
						str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"department\").browseDepartment("
							+ rowIndex
							+ ");'>查看</a>|"
							+ "<a style='font-size:12px;margin-left:12px'   href='javascript:Ext.CUR_APP.getModule(\"department\").editDepartment("
							+ rowIndex
							+ ");'>编辑</a>|"
						
					}else{

					str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"department\").browseDepartment("
							+ rowIndex
							+ ");'>查看</a>|"
							+ "<a style='font-size:12px;margin-left:12px'   href='javascript:Ext.CUR_APP.getModule(\"department\").editDepartment("
							+ rowIndex
							+ ");'>编辑</a>|"
							+ "<a style='font-size:12px;margin-left:12px' href='javascript:Ext.CUR_APP.getModule(\"department\").deleteDepartment("
							+ rowIndex + ");'>删除</a>|"
					}
				}

			} else if (module.app.hasPermission(13)) {

				str = "<a style='font-size:12px' href='javascript:Ext.CUR_APP.getModule(\"department\").browseDepartment("
						+ rowIndex + ");'>查看</a>|"

			};
			return str;
		};

		var getAndRestoreDepartment = function() {

			department_ds = new Ext.data.Store({
						// proxy: new Ext.data.MemoryProxy(myData),
						proxy : new Ext.data.HttpProxy({
									url : Uec3.App.Constants.homeUrl
											+ '/department/base!query.do'
								}),
						baseParams : {
							start : 0,
							limit : 20
						},
						reader : new Ext.data.JsonReader({
									totalProperty : 'totalProperty',
									root : 'root'
								}, [
										{
											name : 'id'
										}, {
											name : 'companyId'
										}, {
											name : 'name'
										}, {
											name : 'isDefault',
											type:'int'
										},{
											name : 'gmtCreate',
											type : 'string'
										}, {
											name : 'gmtModify',
											type : 'string'
										}, {
											name : 'isDelete',
											type : 'int'
										}

								]),
						remoteSort : true,

						// 默认排序字段
						sortInfo : {
							field : "id",
							direction : "asc"
						}

					});
		};

		var componentInitsDepartment = function() {

			var department_colModel = new Ext.grid.ColumnModel([
					new Ext.grid.RowNumberer(),

					{
						header : "操作",
						width : 120,
						dataIndex : 'act',
						renderer :renderDesc
					},{
						header : "ID",
						width : 60,
						dataIndex : 'id',
						hidden : true
					}, {
						header : "companyId",
						width : 60,
						dataIndex : 'companyId',
						hidden : true
					}, {
						header : "部门名称",
						width : 80,
						sortable : true,
						dataIndex : 'name'
					},

					{
						header : "创建时间",
						width : 100,
						dataIndex : 'gmtCreate'
					}, {
						header : "修改时间",
						width : 100,
						dataIndex : 'gmtModify'
					}

			]);
			
			
			// 初始化目录
			var tab = new Ext.TabPanel({
				width : 225,
				region : 'center',
				activeTab : 0,
				items : [{
							title : '目录',
							layout : 'accordion',
							items : [{
										collapsible : true,
										title : '删除记录',
										xtype : 'treepanel',
										width : 225,
										lines : false,
										height : document.body.clientHeight
												* 1.0,
										autoScroll : true,
										split : true,
										loader : new Ext.tree.TreeLoader(),
										root : new Ext.tree.AsyncTreeNode({
													expanded : true,
													children : [{
																text : '全部',
																value : '2',
																leaf : true
															}, {
																text : '未删除',
																value : '0',
																leaf : true
															}, {
																text : '已删除',
																value : '1',
																leaf : true
															}]
												}),
										rootVisible : false,
										listeners : {
											click : function(child) {

												var v = {
													isDelete : child.attributes.value
												};
												var jsonAll = Ext.encode(v);
												department_ds.baseParams = {
													start : 0,
													limit : 20,
													jsonAll : jsonAll
												}
												department_ds.reload();
											}
										}
									}]
						}]
			});

			navigation = new Ext.Panel({
						title : '导航与搜索',
						region : 'west',
						split : true,
						width : 225,
						minSize : 225,
						maxSize : 225,
						collapsible : true,
						lines : false,
						layout : 'fit',
						margins : '3 0 3 3',
						cmargins : '3 3 3 3',
						items : [tab]
					});
			
			// create the Grid
			department_grid = new Ext.grid.GridPanel(

			{
						// title:'部门信息列表',
						region : 'center',
						iconCls : 'icon-grid',
						enableColumnMove : false,
						enableColumnMoveResize : false,
						stripeRows : true,
						height : 600,
						loadMask : {
							msg : "...加载数据中"
						},
						store : department_ds,
						columnLines : false,
						cm : department_colModel,
						sm : new Ext.grid.RowSelectionModel({
									singleSelect : true
								}),
						viewConfig : {
							forceFit : true,
							columnsText : '显示的列',
							scrollOffset : 20,
							sortAscText : '升序',
							sortDescText : '降序'
						},
						tbar : new Ext.app.ModuleToolbar(['-', {
							text : '增加',
							permission:14,
							icon : Uec3.App.Constants.deskUrl
									+ "/resources/images/default/dd/drop-add.gif",
							handler : function() {

								if (!(department_form.getForm().getEl())) {
									department_form.getForm().reset();
								} else {
									department_form.getForm().getEl().dom
											.reset();
								}
								department_form.getForm().findField('id')
										.setValue('');
								department_win.buttons[0].show();
								department_win.buttons[1].show();
								department_win.show();
								department_win.buttons[0].setText('增加');
								department_win.setTitle('增加部门-按Esc退出');
								department_form.setDisabled(false);
							}
						}]),
						bbar : new Ext.PagingToolbar({
									pageSize : 20,
									store : department_ds,
									display : true,
									displayInfo : true,
									displayMsg : '第 {0} - {1} 条  共 {2} 条',
									emptyMsg : "没有记录",
									items : [/**
												 * '-', { pressed: true,
												 * enableToggle:true, text:
												 * 'Show Preview', cls:
												 * 'x-btn-text-icon details',
												 * toggleHandler: function(btn,
												 * pressed){ var view =
												 * department_grid.getView();
												 * view.showPreview = pressed;
												 * view.refresh(); } }
												 */
									]
								})

					});

			//department_ds.load();

			// 初始化表单对象
			department_form = new Ext.form.FormPanel({
						labelAlign : 'right',
						labelWidth : 60,
						// title:客户档案,
						frame : true,
						width : 310,
						autoHeight : true,
						url : '',
						items : [{
									layout : 'form',
									defaultType : 'textfield',
									items : [{
												name : 'id',
												fieldLabel : 'ID',
												xtype : 'hidden'
											}, {
												name : 'companyId',
												fieldLabel : '公司ID',
												xtype : 'hidden'
											}, {
												name : 'name',
												fieldLabel : '部门名称',
												allowBlank:false,
												width:200,
						                        blankText:"部门名称不能为空",
											    maxLength:"30",
												maxLengthText:"最大长度为30位"
											}]
								}]
					});
			department_ajax = new Ext.data.Connection();
			// 初始化window对象
			department_win = new Ext.Window({
						layout : 'fit',
						constraitHeader : true,
						closeAction : 'hide',
						width : 310,
						autoHeight : true,
						autoScroll : true,
						title : '增加部门-按Esc退出',
						collapsible : true,
						constrait : true,
						modal : true,
						draggable : true,
						plain : true,
						header : true,
						resizable : true,
						items : [department_form],
						buttons : [{
							text : '保存',
							iconCls:"icon-save",
							handler : function() {
								if (!department_form.getForm().isValid()) {
									Ext.Msg.alert("提示", "请填写必须项");
									return;

								}
								var formValues = department_form.getForm()
										.getValues();
								var jsonAll = Ext.encode(formValues);
								department_ajax.request({
											url : Uec3.App.Constants.homeUrl
													+ '/department/base!save.do',
											success : function(res) {

												var result = Ext
														.decode(res.responseText);
												if (result.success == "OK") {

													department_win.hide();

													department_ds.reload();

												} else {

													Ext.Msg.alert("提示",
															result.failure);
													
													department_ds.reload();

												}
											},

											failure : function(res) {

												Ext.Msg.alert('失败', "网络出现异常");

											},

											params : {
												jsonAll : jsonAll
											}

										});

							}

						}, {
							text : '关闭',
							iconCls:"icon-close",
							handler : function() {

								department_win.hide();

							}

						}],

						buttonAlign : 'center'

					});

		};
		var controlDepartmentEvent = function() {

			department_ajax.on('beforerequest', function() {

						Ext.MessageBox.wait("保存数据中...", "提示");
					});

			department_ajax.on('requestcomplete', function() {

						Ext.MessageBox.hide();
					});
			
			
			department_win.on("show",function(){
					
				 keymap = new Ext.KeyMap(department_win.id, {
				    key: 13, // or Ext.EventObject.ENTER
				    fn: function(){
			
					if (!department_form.getForm().isValid()) {
						Ext.Msg.alert("提示", "请填写必须项");
						return;

					}
					var formValues = department_form.getForm()
							.getValues();
					var jsonAll = Ext.encode(formValues);
					department_ajax.request({
								url : Uec3.App.Constants.homeUrl
										+ '/department/base!save.do',
								success : function(res) {

									var result = Ext
											.decode(res.responseText);
									if (result.success == "OK") {

										department_win.hide();

										department_ds.reload();

									} else {

										Ext.Msg.alert("提示",
												result.failure);
										
										department_ds.reload();

									}
								},

								failure : function(res) {

									Ext.Msg.alert('失败', "网络出现异常");

								},

								params : {
									jsonAll : jsonAll
								}

							});
					
				},
				    scope: department_win
				});

	    		var maskTopField = new Ext.LoadMaskJUPIT(department_form.id);
	    		module.paramsCollection.add("maskTopField", maskTopField);
			},this,{singe:true});
			

			department_win.on("hide",function(){
					
				keymap.setDisabled(true);
	    		var maskTopField = module.getParamsByKey("maskTopField");
	    		if(maskTopField)maskTopField.hide();
	    		
			},this);
			
			
			/**department_ds.on('load', function() {

						var me = this;
						var records = me.getRange();
						Ext.each(records, function(record) {

									var rowId = me.indexOf(record);

									Ext.getDom('browseDepartment_' + rowId).onclick=function(){

										browseDepartment(rowId);
										
									}

									Ext.get('editDepartment_' + rowId).on(
											'click', function() {

												editDepartment(rowId);

											});

									Ext.get('deleteDepartment_' + rowId).on(
											'click', function() {

												deleteDepartment(rowId);

											});

								})

					});*/

		};

		getAndRestoreDepartment();

		componentInitsDepartment();

		controlDepartmentEvent();

		this.paramsCollection.add("department_ds", department_ds);
		this.paramsCollection.add("department_win", department_win);
		this.paramsCollection.add("department_form", department_form);
		this.paramsCollection.add("department_grid", department_grid);

		return [navigation, department_grid];

	},
	initEvent:function(){
		var module=this;
		var win=module.getParamsByKey("win");
		win.on('show',function(){
			this.getParamsByKey("department_ds").load({
				 callback: function(records,options,success){
		         
		         if(success){
		        	 
		        	// Ext.Msg.alert('提示',"加载数据成功");
		         }else{
		        	 
		        	 
		        	 Ext.Msg.alert('提示',"网络连接异常...请稍候再试");
		         }			  
			
		 }			
	
	});
		},module,{single:true});
	},
	/**
	 * Create this modules window here.
	 */
	createWindow : function() {
		var desktop = this.app.getDesktop();
		var module=this;
		var win = desktop.getWindow('department');
		if (!win) {
			win = desktop.createWindow({
						id : 'department',
						title : '部门列表',
						width : document.body.clientWidth * 1.0,
						height : document.body.clientHeight * 1.0,
						iconCls : 'acc-icon',
						shim : false,
						animCollapse : false,
						constrainHeader : true,
						maximizable : true,
						maximized : true,
						taskbuttonTooltip : "部门列表",
						layout : "fit",
						layout : "border",
						resizable : true,
						tools : [{
									id : 'refresh',
									handler : Ext.emptyFn,
									scope : this
								}],
						items : [this.getComponents(module)]
					});
			 module.paramsCollection.add("win",win);
	         module.initEvent();
		}
		win.show();
	}
});